
(function () {
    var request = {
        host: "",
        getToken: function () {
            return sessionStorage.token;
        },
        ajax: function (o) {
            if (o.urlParams) {
                o.url = this.joinUrlParams(o.url, o.urlParams);
            }
            if (!o.async) {
                o.async = false;
            }
            $.ajax({
                type: o.type,
                url: this.host + o.url,
                headers: {
                    "token": this.getToken(),
                    "Content-Type": "application/json"
                },
                data: JSON.stringify(o.data),
                async: o.async,
                success: function (result) {
                    if (result.StatusCode == 401) {
                        sessionStorage.token = "";
                        common.confirm("", result.message, function () {
                            window.top.location.href = "/Login/Login";
                        });
                        return;
                    }
                    o.success(result);
                },
                error: function (err) {
                    if (err.status == 401) {
                        sessionStorage.token = "";
                        common.confirm("", err.responseText, function () {
                            window.top.location.href = "/Login/Login";
                        });
                        return;
                    }
                    if (o.error) {
                        o.error(err);
                    }
                    else {
                        common.errorMsg("出现异常");
                    }
                }
            });
        },
        headers: function (o) {
            if (!o) {
                o = {
                    "Content-Type": "application/json"
                };
            }
            o.token = this.getToken();
            return o;
        },
        joinUrlParams: function (url, data) {
            //拼接URL参数
            var paramStr = "";
            Object.keys(data).forEach(function (key) {
                if (paramStr == "") {
                    paramStr = key + "=" + data[key];
                }
                else {
                    paramStr += "&" + key + "=" + data[key];
                }
            });
            if (url.indexOf('?') == -1) {
                url = url + "?" + paramStr;
            }
            return url;
        }
    }
    window.request = request;
})();

